using sockets, system;

const path = "server_socket";
extern int unlink(char *name);

server = loop with
  loop = loop if ~null s && ~response fp s when
    // Connect to a client.
    cfd = accept fd $ sockaddr ();
    // Open the client socket as a FILE* and read a request.
    fp = fdopen cfd "r+"; s = fgets fp;
  end;
  loop = puts "server is exiting" $$ closesocket fd $$
         unlink path $$ () otherwise;
  response fp s::string = s=="quit\n" when
    // Process the request. (Here we just print the received
    // message and echo it back to the client.)
    printf "server> %s" s;
    fputs s fp;
  end;
end when
  // Create the server socket and start listening.
  unlink path;
  fd = socket AF_UNIX SOCK_STREAM 0;
  bind fd (sockaddr path); listen fd 5;
  printf "server listening at '%s'\n" path;
end;

server;

